package myjava.k_annotation.mapper.impl;


import myjava.k_annotation.annotation.AnoField;
import myjava.k_annotation.annotation.AnoTable;
import myjava.k_annotation.config.DataSource;
import myjava.k_annotation.mapper.UserMapper;
import org.apache.log4j.Logger;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * @Auther: cty
 * @Date: 2020/3/2 21:26
 * @Description:
 * @version: 1.0
 */
public class UserMapperImpl implements UserMapper {

    // 加载日志对象
    Logger log = Logger.getLogger(UserMapperImpl.class);

    /**
     * 根据注解信息创建数据表
     * @param beanClz
     * @return
     */
    @Override
    public void CreateTable(Class<?> beanClz) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            //1. 加载MySQL驱动程序
            //Class.forName("com.mysql.jdbc.Driver");
            // 高版本（如MySQL 8 驱动）加载的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2. 获得数据库连接
            conn = DriverManager.getConnection(DataSource.URL, DataSource.USER, DataSource.PASSWORD);

            //3. 操作数据库，实现增删改查
            //通过PreparedStatement进行参数传递，实现存入一条记录
            String createSql = getCreateSql(beanClz);
            log.info("建表SQL：" + createSql);
            ps = conn.prepareStatement(createSql);
            ps.execute();

            //4. 处理返回数据——如果有数据，rs为更新的行数
        } catch (ClassNotFoundException e) {
            log.debug("加载MySQL驱动失败");
            e.printStackTrace();
        } catch (SQLException e) {
            log.debug("数据库连接失败或SQL执行失败");
            e.printStackTrace();
        } finally {
            //5. 关闭连接
            try {
                if(ps!=null){
                    ps.close();
                }
            } catch (SQLException e) {
                log.debug("关闭ps失败");
                e.printStackTrace();
            }

            try {
                if(conn!=null){
                    conn.close();
                }
            } catch (SQLException e) {
                log.debug("关闭conn失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取建表Sql
     *
     * @param beanClz
     * @return
     */
    private String getCreateSql(Class<?> beanClz) {
        StringBuilder createSql = new StringBuilder();
        String tableName = beanClz.getDeclaredAnnotation(AnoTable.class).value();
        createSql.append("create table if not exists ").append(tableName);

        Field[] fields = beanClz.getDeclaredFields();
        StringJoiner fieldsSql = new StringJoiner(", ", "(", ")");
        for (Field field : fields) {
            AnoField anoField = field.getDeclaredAnnotation(AnoField.class);
            if (Objects.nonNull(anoField)) {
                fieldsSql.add(new StringJoiner(" ").add(anoField.fieldName()).add(anoField.fieldType()).add(anoField.constraint()).toString());
            }
        }
        return createSql.append(fieldsSql).toString();
    }
}
